// AI对话服务
export interface ProductItem {
  id: number
  name: string
  price: number
  image: string
  description: string
  category: string
  rating: number
  sales: number
}

export interface AIResponse {
  text: string
  products?: ProductItem[]
  type: 'text' | 'product_recommendation' | 'greeting' | 'help'
}

export interface ChatContext {
  userMessage: string
  timestamp: number
  intent?: string
}

class AIService {
  private chatHistory: ChatContext[] = []
  
  // 模拟商品数据库
  private products: ProductItem[] = [
    {
      id: 1,
      name: 'iPhone 15 Pro',
      price: 7999,
      image: 'https://picsum.photos/200/200?random=1',
      description: '最新款iPhone，配备A17 Pro芯片，钛金属设计',
      category: '手机',
      rating: 4.8,
      sales: 1250
    },
    {
      id: 2,
      name: 'MacBook Air M2',
      price: 8999,
      image: 'https://picsum.photos/200/200?random=2',
      description: '轻薄便携，M2芯片强劲性能',
      category: '电脑',
      rating: 4.9,
      sales: 890
    },
    {
      id: 3,
      name: 'AirPods Pro 2',
      price: 1899,
      image: 'https://picsum.photos/200/200?random=3',
      description: '主动降噪，空间音频体验',
      category: '耳机',
      rating: 4.7,
      sales: 2100
    },
    {
      id: 4,
      name: 'iPad Pro 12.9',
      price: 6999,
      image: 'https://picsum.photos/200/200?random=4',
      description: 'M2芯片，Liquid Retina XDR显示屏',
      category: '平板',
      rating: 4.8,
      sales: 650
    },
    {
      id: 5,
      name: 'Apple Watch Series 9',
      price: 2999,
      image: 'https://picsum.photos/200/200?random=5',
      description: '健康监测，智能手表',
      category: '手表',
      rating: 4.6,
      sales: 1800
    },
    {
      id: 6,
      name: '小米13 Ultra',
      price: 5999,
      image: 'https://picsum.photos/200/200?random=6',
      description: '徕卡影像，骁龙8 Gen2',
      category: '手机',
      rating: 4.5,
      sales: 980
    },
    {
      id: 7,
      name: 'Sony WH-1000XM5',
      price: 2399,
      image: 'https://picsum.photos/200/200?random=7',
      description: '业界领先降噪，30小时续航',
      category: '耳机',
      rating: 4.8,
      sales: 1200
    },
    {
      id: 8,
      name: 'Dell XPS 13',
      price: 7299,
      image: 'https://picsum.photos/200/200?random=8',
      description: '13英寸超轻薄笔记本',
      category: '电脑',
      rating: 4.4,
      sales: 560
    }
  ]

  // 关键词映射
  private keywordMap = {
    手机: ['手机', '电话', 'phone', 'iphone', '小米', '华为', '三星'],
    电脑: ['电脑', '笔记本', 'laptop', 'macbook', '联想', '戴尔', 'dell'],
    耳机: ['耳机', '音响', '音频', 'airpods', '索尼', 'sony'],
    平板: ['平板', 'ipad', '平板电脑'],
    手表: ['手表', '智能手表', 'watch', 'apple watch'],
    价格: ['价格', '多少钱', '便宜', '贵', '优惠', '折扣'],
    推荐: ['推荐', '建议', '什么好', '哪个好', '选择']
  }

  // 分析用户意图
  private analyzeIntent(message: string): string {
    const lowerMessage = message.toLowerCase()
    
    // 检查是否询问价格
    if (this.keywordMap.价格.some(keyword => lowerMessage.includes(keyword))) {
      return 'price_inquiry'
    }
    
    // 检查是否要推荐
    if (this.keywordMap.推荐.some(keyword => lowerMessage.includes(keyword))) {
      return 'recommendation'
    }
    
    // 检查商品类别
    for (const [category, keywords] of Object.entries(this.keywordMap)) {
      if (keywords.some(keyword => lowerMessage.includes(keyword))) {
        return `product_${category}`
      }
    }
    
    return 'general'
  }

  // 根据关键词搜索商品
  private searchProducts(message: string, limit: number = 3): ProductItem[] {
    const lowerMessage = message.toLowerCase()
    const results: ProductItem[] = []
    
    // 精确匹配
    for (const product of this.products) {
      if (product.name.toLowerCase().includes(lowerMessage) || 
          product.description.toLowerCase().includes(lowerMessage)) {
        results.push(product)
      }
    }
    
    // 类别匹配
    if (results.length < limit) {
      for (const [category, keywords] of Object.entries(this.keywordMap)) {
        if (keywords.some(keyword => lowerMessage.includes(keyword))) {
          const categoryProducts = this.products.filter(p => 
            p.category === category && !results.includes(p)
          )
          results.push(...categoryProducts)
        }
      }
    }
    
    // 按销量和评分排序
    return results
      .sort((a, b) => (b.rating * b.sales) - (a.rating * a.sales))
      .slice(0, limit)
  }

  // 生成AI回复
  async generateResponse(userMessage: string): Promise<AIResponse> {
    // 添加到聊天历史
    this.chatHistory.push({
      userMessage,
      timestamp: Date.now()
    })

    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 800 + Math.random() * 1200))

    const intent = this.analyzeIntent(userMessage)
    const lowerMessage = userMessage.toLowerCase()

    // 问候语
    if (lowerMessage.includes('你好') || lowerMessage.includes('hello') || 
        lowerMessage.includes('hi') || this.chatHistory.length === 1) {
      return {
        text: '您好！我是您的购物助手小智 🤖\n\n我可以帮您：\n• 推荐合适的商品\n• 查询商品信息和价格\n• 解答购物相关问题\n\n请告诉我您想要什么商品，或者有什么问题需要咨询？',
        type: 'greeting'
      }
    }

    // 帮助信息
    if (lowerMessage.includes('帮助') || lowerMessage.includes('help')) {
      return {
        text: '我可以为您提供以下服务：\n\n📱 商品推荐\n• "推荐一款手机"\n• "有什么好的耳机"\n\n💰 价格查询\n• "iPhone多少钱"\n• "最便宜的电脑"\n\n🛒 购物建议\n• "学生适合什么电脑"\n• "运动用什么耳机"\n\n还有其他问题吗？',
        type: 'help'
      }
    }

    // 商品相关查询
    const products = this.searchProducts(userMessage)
    
    if (products.length > 0) {
      let responseText = ''
      
      if (intent === 'price_inquiry') {
        responseText = `为您找到以下商品的价格信息：\n\n`
        products.forEach(product => {
          responseText += `💰 ${product.name}：¥${product.price}\n`
        })
        responseText += '\n点击商品卡片可以查看详情并购买哦！'
      } else {
        responseText = this.generateProductRecommendationText(userMessage, products)
      }
      
      return {
        text: responseText,
        products,
        type: 'product_recommendation'
      }
    }

    // 通用回复
    return {
      text: this.generateGeneralResponse(userMessage),
      type: 'text'
    }
  }

  // 生成商品推荐文本
  private generateProductRecommendationText(userMessage: string, products: ProductItem[]): string {
    const responses = [
      `根据您的需求，我为您推荐以下${products.length}款商品：`,
      `为您精选了${products.length}款热门商品：`,
      `这些商品很适合您：`,
      `根据销量和评价，推荐这些商品：`
    ]
    
    let text = responses[Math.floor(Math.random() * responses.length)] + '\n\n'
    
    products.forEach((product, index) => {
      text += `${index + 1}. ${product.name}\n`
      text += `   💰 ¥${product.price} | ⭐ ${product.rating}分 | 🔥 已售${product.sales}件\n`
    })
    
    text += '\n点击商品卡片查看详情，喜欢的话可以直接购买哦！'
    
    return text
  }

  // 生成通用回复
  private generateGeneralResponse(userMessage: string): string {
    const responses = [
      '抱歉，我没有完全理解您的问题。您可以尝试：\n• 询问具体商品："推荐一款手机"\n• 查询价格："iPhone多少钱"\n• 寻求建议："学生用什么电脑好"',
      '我是购物助手，主要帮助您选购商品。请告诉我您想要什么类型的商品，我会为您推荐最合适的选择！',
      '您可以问我关于商品的任何问题，比如价格、功能、推荐等。我会尽力为您提供帮助！',
      '如果您在寻找特定商品，请告诉我商品类型或品牌，我会为您推荐最受欢迎的选择。'
    ]
    
    return responses[Math.floor(Math.random() * responses.length)]
  }

  // 获取热门商品
  getHotProducts(limit: number = 4): ProductItem[] {
    return this.products
      .sort((a, b) => b.sales - a.sales)
      .slice(0, limit)
  }

  // 获取推荐商品
  getRecommendedProducts(category?: string, limit: number = 4): ProductItem[] {
    let filteredProducts = this.products
    
    if (category) {
      filteredProducts = this.products.filter(p => p.category === category)
    }
    
    return filteredProducts
      .sort((a, b) => (b.rating * b.sales) - (a.rating * a.sales))
      .slice(0, limit)
  }

  // 清除聊天历史
  clearHistory(): void {
    this.chatHistory = []
  }
}

// 导出单例实例
export const aiService = new AIService()